/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.classifiers;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * A Filter chain-of-responsibility.
 * 
 * <p>
 * This class implement the pattern chain-of-responsibility of {@link Filter}s
 * </p>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: FilterChain.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class FilterChain {

	/** List containig the filters */
	private final List/*Filter*/ filters = new LinkedList();

	/**
	 * Add a {@link Filter} to the filters list.
	 * 
	 * @param filter
	 *            The Filter to add.
	 */
	public void add(Filter filter) {
		filters.add(filter);
	}

	/**
	 * Iterate over the filters list to find a {@link Filter} can handle the
	 * given user-agent.
	 * 
	 * @param userAgent
	 *            The user-agent associated with given device's id.
	 * @param deviceID
	 *            The device's id to collect.
	 */
	public void filter(String userAgent, String deviceID) {

		for (Iterator iterator = filters.iterator(); iterator.hasNext();) {
			Filter filter = (Filter) iterator.next();
			if (filter.canHandle(userAgent)) {
				filter.filter(userAgent, deviceID);
				break;
			}
		}
	}

	/**
	 * Returns the {@link FilteredDevices} containing the given user-agent.
	 * 
	 * @param userAgent
	 *            The user-agent used to find {@link FilteredDevices}.
	 * @return The {@link FilteredDevices} instance containing given user-agent.
	 */
	public FilteredDevices getFilteredDevices(String userAgent) {

		for (Iterator iterator = filters.iterator(); iterator.hasNext();) {
			Filter filter = (Filter) iterator.next();
			if (filter.canHandle(userAgent)) {
				return filter.getFilteredDevices();
			}
		}

		return new FilteredDevices();
	}

}
